<?php

namespace App\Http\Controllers;

use App\Models\MovieWatchUser;
use Illuminate\Http\Request;
use App\Models\Movie;
use App\Crawlers\MovieInfoCrawler;
use Illuminate\Support\Facades\Storage;
use QL\QueryList;
use Illuminate\Support\Str;
use App\Models\PlayerSource;
use App\Models\PlayerType;
use App\Bots\CommentBots;
use App\Bots\CreateUserBots;
use App\Services\Alibaba\Ali;
use App\Models\User;
class PagesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('welcome');
    }


    public function explore(Movie $movie, User $user)
    {
        $count = MovieWatchUser::count();
        $query = $movie->whereHas('bingeWatchers', function ($query) use ($user) {
            $query->where('user_id', $user->id)->where('status', 'watched');
        })->newUpdated();
        $movies = $query->paginate(10);
        // 解析用户是否看过
        $watchs = $user->watchStatusWithMovies($movies->pluck('id'));
        return view('pages.explore', compact('count', 'movies'));
    }

    public function crawler(Request $request, MovieInfoCrawler $crawler)
    {
        $id = $request->id;
        $url = config('services.oss.douban.url') . '/' . $id;

        $ql = QueryList::get($url);

        //$result = $ql->find('.gray_ad')->html();

        // if(!$result) return '没有采集到信息';
        return dd($this->analysePlaySource($ql));
        // 模拟设置一个 电影模型
        $movie = Movie::doesntHave('player_sources')->first();
        foreach ($this->analysePlaySource($ql) as $player) {
            $type = PlayerType::firstOrCreate(
                ['type' => $player['type']],
                ['name' => $player['name']]
            );

            $playerData = [
                'type_id' => $type->id,
                'is_free' => $player['is_free'],
                'is_vip_free' => $player['is_vip_free'],
                'content' => $player['content'],
                'url' => $player['url'],
                'movie_id' => $movie->id,
            ];
            PlayerSource::create($playerData);
        }
        dd(PlayerSource::all());

    }
    public function test()
    {
        $result = app(Ali::class)->green('dsad565');
        dd($result);
    }

    public function analysePlaySource($ql)
    {
        $rules = [
            'name' => ['a.playBtn', 'data-cn'], // 在哪里看
            'player_url' => ['a.playBtn', 'href'], // 唯一地址
            'content' => ['span.buylink-price', 'text'], // 简单的内容 (会员免费看...)
        ];
        $range = '.gray_ad li';
        $result = $ql->range($range)->rules($rules)->query()->getData()->map(function($item){
            $item['content'] = trim($item['content']);
            $item['player_url'] = urldecode(str_replace('https://www.douban.com/link2/?url=', '', $item['player_url']));
            // 解析出 具体网站

            $site = parse_url($item['player_url']);


            if ( ! isset($site['host'])) {
                return;
            }
            if(isset($site['fragment']) && ! isset($site['query'])) {
                $item['player_url'] = str_replace('#', '?', $item['player_url']);
            } else if ( ! isset($site['query']) && Str::contains($item['player_url'], '&')) {
                $item['player_url'] = Str::replaceFirst('&', '?', $item['player_url']);
            } else {
                $item['player_url'] .= '?rweoryewou54370fsbfds=1';
            }

            $site = parse_url($item['player_url']);
            // 重新组织 url
            $item['url'] = $site['scheme'] . '://' . $site['host'] . $site['path'];
            $item['is_free'] = $item['content'] === '免费观看' ? true : false;
            $item['is_vip_free'] = Str::contains($item['content'], '付费') ? false : true;

            parse_str($site['query'], $player_query);
            $item['type'] = $player_query['subtype'];

            return $item;
        });
        return $result->filter()->all();
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
